package com.graduation_design.modules.app.interceptor;

import com.graduation_design.common.exception.HubException;
import com.graduation_design.common.lang.Const;
import com.graduation_design.modules.app.annotation.Login;
import com.graduation_design.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    // 自定义token的拦截器

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 判断是否有@Login注解，没有就放行
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }

        if(annotation == null){
            return true;
        }

        // 获取用户凭证token
        String token = request.getHeader("token");

        // 判断token是否合法，凭证是否为空
        if(!StringUtils.hasText(token)){
            throw new UnauthenticatedException("请先登录");
        }

        Claims claims = jwtUtils.getClaimByToken(token, "APP");
        if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){
            throw new UnauthenticatedException("请先登录");
        }

        // 把用户信息存到session，设置userId到request里，后续根据userId，获取用户信息
        request.getSession().setAttribute(Const.USER_KEY, Long.parseLong(claims.getSubject()));

        return true;
    }
}
